package com.xcity.db.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;
import com.xcity.game.pet.Pet;
import com.xcity.game.pet.PetManager;

import naga.x.util.StringUtils;

public class PetsTypeHandler extends BaseTypeHandler<PetManager> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, PetManager parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, parameter != null ? parameter.toString() : null);
	}

	@Override
	public PetManager getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return parse(rs.getString(columnName));
	}

	@Override
	public PetManager getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return parse(rs.getString(columnIndex));
	}

	@Override
	public PetManager getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return parse(cs.getString(columnIndex));
	}
	
	private static PetManager parse(String json) {
		if (StringUtils.isEmpty(json)) {
			return new PetManager(null, null);
		}
		return new PetManager(null, JSON.parseArray(json, Pet.class));
	}
	
}
